﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using MailMerge.Infrastructure;

namespace MailMerge.Builders
{
	public class MergeBuilder : DocumentBuilder<List<ArrearsModel>>
	{
		public MergeBuilder(List<ArrearsModel> model) : base(model)
		{
		}

		public override string TemplateFileName
		{
			get
			{
				return
					string.IsNullOrWhiteSpace(base.TemplateFileName)
					? "Documents/MergeContainer.docx"
					: base.TemplateFileName;
			}
			set
			{
				base.TemplateFileName = value;
			}
		}

		public override void Build(string outputPath)
		{
			base.Build(outputPath);
			
			var placeHolder = Document.GetContentControls().Single(cc => cc.Tag == "Page");
			
			for (int index = 0; index < Model.Count; index++)
			{
				var arrearsModel = Model[index];
				var tempfile = Path.GetRandomFileName();
				
				using (var builder = new ArrearsBuilder(arrearsModel))
				{
					builder.Build(tempfile);
				}

			
				placeHolder.Self.ReplaceContent(tempfile, "arrears" + index);
				File.Delete(tempfile);
			}

			placeHolder.Self.Remove();
		}
	}
}
